
[filename1,ax1,ay1] = fileprepro();

[filename2,ax2,ay2] = fileprepro();

figure("Name", [filename1, ' - ', filename2, '加速度时频对比']);

subplot(2,2,1);

fs = 1000;          % 采样频率 (Hz)

window = hann(128);      % 汉宁窗，窗口长度为2128
noverlap = 64;%round(0); % 重叠长度，50%重叠
nfft = 256;                 % FFT点数

% 计算 STFT
[s, f, t_stft] = spectrogram(ax1, window, noverlap, nfft, fs, 'yaxis');

% 计算幅度谱并转换为分贝（dB）单位
s_db = 20*log10(abs(s));

imagesc(t_stft, f, s_db);
axis xy; % 将 y 轴方向反转，使频率从低到高显示
title([filename1,' - X加速度']);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
caxis([-100,10]);
ylim([0,50]);
%colormap('jet'); % 设置颜色映射为 'jet'
%freezeColors;

subplot(2,2,2);


% 计算 STFT
[s, f, t_stft] = spectrogram(ay1, window, noverlap, nfft, fs, 'yaxis');

% 计算幅度谱并转换为分贝（dB）单位
s_db = 20*log10(abs(s));

imagesc(t_stft, f, s_db);
axis xy; % 将 y 轴方向反转，使频率从低到高显示

title([filename1,' - Y加速度']);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
caxis([-100,10]);
ylim([0,50]);

subplot(2,2,3);

% 计算 STFT
[s, f, t_stft] = spectrogram(ax2, window, noverlap, nfft, fs, 'yaxis');

% 计算幅度谱并转换为分贝（dB）单位
s_db = 20*log10(abs(s));

imagesc(t_stft, f, s_db);
axis xy; % 将 y 轴方向反转，使频率从低到高显示
title([filename2,' - X加速度']);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
caxis([-100,10]);
ylim([0,50]);
%colormap('jet'); % 设置颜色映射为 'jet'
%freezeColors;

subplot(2,2,4);

% 计算 STFT
[s, f, t_stft] = spectrogram(ay2, window, noverlap, nfft, fs, 'yaxis');

% 计算幅度谱并转换为分贝（dB）单位
s_db = 20*log10(abs(s));

imagesc(t_stft, f, s_db);
axis xy; % 将 y 轴方向反转，使频率从低到高显示

title([filename2,' - Y加速度']);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
caxis([-100,10]);
ylim([0,50]);

colormap('jet'); % 设置颜色映射为 'jet'

h = colorbar('Position', [0.93 0.11 0.015 0.81], 'Location', 'eastoutside');
h.Label.String = '分贝 (dB)';


function [filename, ax,ay] = fileprepro()

    [filename, pathname] = uigetfile('*.txt');  % 默认显示所有文件
    
    if filename == 0
        return;
    end

    fullname = fullfile(pathname, filename);

    data = importdata(fullname, ' ');

    %x = data(:, 1);
    %y = data(:, 2);

    x = data(:, 2);
    y = data(:, 3);
    
    vx = [zeros(1,1); diff(x)];
    ax = [zeros(1,1); diff(vx)];
    
    vy = [zeros(1,1); diff(y)];
    ay = [zeros(1,1); diff(vy)];

    figure('Name', [filename, ' - 轨迹']);
    scatter(x, y, 'filled');  % 绘制二维散点图
    xlabel('X');  % X 轴标签
    ylabel('Y');  % Y 轴标签
    title('轨迹图');  % 图形标题
    grid on;  % 开启网格
end